$(document).ready(function() {
  //初始化编辑器
  $(".summernote").summernote({
    lang: 'zh-CN',
    oninit: function() {
      summernote = this;
    },
    onfocus: function() {
    },
    onblur: function() {
    },
    onImageUpload: function() {
    },
    onToolbarClick: function() {
    }
  })

  //这个视频地址
  // http://zy.down.99.com//gw/yhzl/video/act/2017/qmls-1121-1.mp4

  //初始化事件
  var img = $('img');
  getInputDelayTrigger($('#img'), function(data) {
    if (data) {
      $('#show-img').removeClass('hide').find('img').attr('src', data);
    } else {
      $('#show-img').addClass('hide').find('img').attr('src', '');
    }
  })

  //新增或者编辑文章
  addOrEditJson();
  function addOrEditJson() {
    var $articleId = $('#articleId');
    var $title = $('#title');
    var $type = $('#type');
    var $author = $('#author');
    var $img = $('#img');
    var $sub_title = $('#sub_title');
    var $keywords = $('#keywords');
    var $source = $('#source');
    var $summernote = $('.summernote');
    var $attachmentsNotation = $('#attachments_notation');
    var $relativeArticle = $('#relative_article');
    var fileIds = "";

    var saveArticleButton = $('.saveArticle');
    saveArticleButton.click(function() {
      fileIds = saveArticleButton.attr("fileIds");
      saveArticleButton.html('更新中...');
      saveArticleHandler({}, function() {
        saveArticleButton.html('更新');
      });
    });
    /**
     * @description 保存文章
     * @author xiezuobing[948466]<435321508@qq.com>
     * @param {any} values 
     */
    function saveArticleHandler(values, callback) {

      values = values || {};
      var params = {
        title: $title.val(),
        type: $type.val(),
        author: $author.val(),
        img: $img.val(),
        sub_title: $sub_title.val(),
        keywords: $keywords.val(),
        content: $summernote.code(),
        file_ids: fileIds,
        attachments_notation: $attachmentsNotation.val(),
        relative_article: $relativeArticle.val()
      };
      if ($articleId.val())
        params.id = $articleId.val();
      $.extend(params, values);
      $.ajax({
        method: 'post',
        url: '/admin/article/addOrEdit',
        data: params,
        dataType: 'json',
        headers: {
          "x-csrf-token": saveArticleButton.attr("x-csrf-token")
        },
        success: function(data) {
          if (!params.id) {
            createHandler(data)
          } else {
            layer.msg('更新成功~');
            callback && callback(data);
          }
        },
        fail: function(err) {
          console.log(err);
        }
      });
    }
    //创建的处理方式
    function createHandler(data) {
      var tab = $(window.parent.document).find('.active.J_menuTab');
      var a = $('<a></a>').attr('tabname', '编辑文章 | ' + data.title).attr('href', '/admin/article/edit?articleId=' + data.id).addClass('J_menuItem');
      a.click(window.parent.goToTabFrame).click();
      tab.find('i').click();
    }

    //添加附件
    addAttachment();
    var selectPop;
    function addAttachment() {
      var $addAttachment = $('.add-attachment');
      $addAttachment.click(function() {
        selectPop = layer.open({
          type: 2,
          title: '添加附加文件',
          shadeClose: true,
          shade: 0.8,
          // closeBtn: 0,
          // shade: false,
          // maxmin: true,
          area: ['90%', '90%'],
          content: '/admin/resource/select?select=1' //iframe的url
        });
      });
    }
    
    var $attachmentList = $('.attachment-list');
    $attachmentList.on('click', '.close', function() {
      var that = this;
      var pop = layer.confirm('您确认删除该附加文件吗？', {
        btn: ['确定', '取消'] //按钮
      }, function() {
        $(that).parent().remove();
        getSelectIds();
        layer.close(pop);
      }, function() {
        layer.close(pop);
      })

    });
    initGlobalChoose();
    function initGlobalChoose() {

      window.fileChooseHandler = function(data) {
        $attachmentList.empty();
        $('.saveArticle').attr('fileIds', data.ids);
        $(data.files).each(function() {
          var formControl = $('<div class="file-item form-control no-border clearfix"></div>');
          formControl.attr('fileId', this.fileId)
          if (this.type == 1) formControl.append('<i class="fa fa-picture-o text-success" aria-hidden="true"></i>');
          else if (this.type == 2) formControl.append('<i class="fa fa-file-pdf-o text-success" aria-hidden="true"></i>');
          else if (this.type == 3) formControl.append('<i class="fa fa-video-camera text-success" aria-hidden="true"></i>');
          formControl.append(' <a href="' + this.url + '" target="_blank" class="text-success">' + this.filename + '</a>');
          var close = $('<span class="close" title="删除' + this.filename + '"><i class="fa fa-times" aria-hidden="true"></i></span>');
          formControl.append(close);
          $attachmentList.append(formControl);
          // close.click(function() {
          //   layer.confirm('您确认删除该条文件吗？', {
          //     btn: ['确定', '取消'] //按钮
          //   }, function() {
          //     formControl.remove();
          //     getSelectIds();
          //   }, function() {})
          // });
        });
        if (selectPop) {
          layer.close(selectPop);
          selectPop = null;
        }
      }
    }
    function getSelectIds() {
      var ids = [];
      $attachmentList.find('.file-item').each(function() {
        ids.push($(this).attr("fileId"));
      });
      console.log(ids);
      $('.saveArticle').attr('fileIds', ids.join(","));
    }

    /**
     * @description 发布| 取消发布
     * @author xiezuobing[948466]<435321508@qq.com>
     */
    togglePublish();
    function togglePublish() {
      var $publishOptBtn = $('#publish_optBtn');
      var icon = $publishOptBtn.find('i');
      var span = $publishOptBtn.find('span');
      var button = $publishOptBtn.find('button');
      var articleId = button.attr('articleId');
      button.click(function() {
        var publish = button.attr('publish');
        publishJson(articleId, function() {
          if (publish == 0) {
            button.attr('publish', 1).html('取消发布');
            icon.addClass('fa-eye').removeClass('fa-eye-slash');
            span.html('状态：已发布');
          } else {
            button.attr('publish', 0).html('发布');;
            icon.removeClass('fa-eye').addClass('fa-eye-slash');
            span.html('状态：未发布');
          }
        });
      });
    }

    function publishJson(articleId, callback) {
      $.ajax({
        url: '/admin/article/togglePublish?articleId=' + articleId,
        dataType: 'json',
        success: function(data) {
          toastProp(data, callback);
        },
        fail: function(err) {
          console.log(err);
        }
      });
    }
    //弹出窗口
    function toastProp(data, callback) {
      if (data.errCode == 0) {
        layer.msg(data.errMsg, {
          time: 2000
        });
        callback && callback();
      } else {
        layer.msg(data.errMsg);
      }
    }
  }


});